from plugin import plugin
import pickle, datetime
from threading import Timer

__doc__ = "stats"

class stats(plugin):
	"Collects IRC stats"
	
	def __init__(self):
		self._version = '3.0 development'
		self.reminder =  None
		self._nicks = {}
		self._emotes = [':)', ';)', ':]', ':D', ':S', ':/', ':>', ':<', ';D', ':P', ';p', ':p', ';P', '^^', 'D:']
		self._happy_emotes = [x for x in self._emotes if x.endswith(')') or x.endswith('D') or x.endswith('>')]
		self._sad_emotes = [x for x in self._emotes if x.endswith('(') or x.startswith('D') or x.endswith('<')]
		dt = datetime.datetime.now()
		self._createTimer(86400 - (((dt.hour * 60) + dt.minute) * 60))

	def __del__(self):
		if self.reminder:
			self.reminder.cancel()
	
	def _createTimer(self, time):
		try:
			t = Timer(time, self._onDayChange)
			t.start()
			self.reminder = t
		except:
			print 'Error creating timer'
			pass
		
	def _onDayChange(self):
		self._createTimer(86400)
		print 'Day change detected'

	def _process(self, msg):
		user = self._nicks[msg['sender']['name']]
		for word in msg['data'].split():
			if word in self._emotes:
				if word not in user['emotes']:
					user['emotes'][word] = 0
				user['emotes'][word] = user['emotes'][word] + 1

	def _onMessage(self, msg):
		nick = msg['sender']['name']
		if nick not in self._nicks:
			self._nicks[nick] = {
				"emotes":{},
				"lines_per_day":[],
				"average_words_per_line":[],
				"commands_used":{},
				"relations":[],
				"favourite_words":[],
			}
		if msg['type'] == 'privmsg':
			self._process(msg)
	
